import { AnyAction, Reducer } from 'redux';
import { message } from 'antd';
import { EffectsCommandMap } from 'dva';
import { fetchValidation } from '@/utils';
import {
  queryLogisRegionList,
  operSaveCabs,
  operDeleteCabinet,
  querySaveList,
} from './service';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetchLogisRegion: Effect;
    saveCabs: Effect;
    delete: Effect;
    saveList: Effect;
  };
  reducers: {
    saveData: Reducer;
    saveCab: Reducer;
  };
}

const Model: ModelType = {
  namespace: 'partitionManagementCabinet',

  state: {
    dataInfo: {
      count: 0,
      list: [],
    },
    saveInfo: {
      count: 0,
      list: [],
    },
    logisList: [],
  },

  effects: {
    * fetchLogisRegion({ payload }, { call, put }) {
      const response = yield call(queryLogisRegionList, payload);
      yield put({
        type: 'saveData',
        payload: response.body || { count: 0, list: [] },
      });
    },

    * saveCabs({ payload: { search, ...query } }, { call, put }) {
      const response = yield call(operSaveCabs, query);
      const data = fetchValidation(response);
      if (data.code === 0) {
        message.success('添加成功');
        yield put({
          type: 'fetchLogisRegion',
          payload: search,
        });
      }
    },

    * delete({ payload: { search, ...query } }, { call, put }) {
      const response = yield call(operDeleteCabinet, query);
      const data = fetchValidation(response);
      if (data) {
        message.success('删除成功');
        yield put({
          type: 'fetchLogisRegion',
          payload: search,
        });
      }
    },

    * saveList({ payload }, { call, put }) {
      payload = {
        pageIndex: 1,
        pageSize: 20,
        ...payload,
      };
      const response = yield call(querySaveList, payload);
      yield put({
        type: 'saveCab',
        payload: response.body || { count: 0, list: [] },
      });
    },
  },

  reducers: {
    saveData(state, action) {
      return ({
        ...state,
        dataInfo: action.payload,
      });
    },

    saveCab(state, action) {
      return ({
        ...state,
        saveInfo: action.payload,
      });
    },
  },
};

export default Model;
